<?php

require_once WACT_ROOT . '/db/db.inc.php';
require_once WACT_ROOT . '/util/dataspace.inc.php';
require_once APP_ROOT . "model/common/session.php";
require_once APP_ROOT . "model/common/user.php";
require_once APP_ROOT . "model/common/parameters.php";
require_once APP_ROOT . "model/common/price.php";
require_once APP_ROOT . "model/common/date.php";

class SubscriptionFilter {
	var  $paypal_url;
    var  $paypal_email;

    function SubscriptionFilter() {
        $mode = Parameters::getRunningMode();
     	if ($mode) $this->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
     	else  $this->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';

     	$this->paypal_email = Parameters::getPaypalEmail();
    }

    function doFilter(&$vars){


     	$vars['paypal_url'] = $this->paypal_url;
        $vars['business'] = urlencode($this->paypal_email);

    	switch($vars['type']){
    		case 1: $vars['type']='3-days';
    			break;
    		case 2: $vars['type']='7-days';
    			break;
    		case 3: $vars['type']='30-days reccuring';
    			break;
    		case 4: $vars['type']='1 year recurring';
    			break;
    	}
    	if($vars['status']==1)  {
    		$vars['status']='Active';
            $vars['active']=1;
    	} else {
    		$vars['status']='Finished';
            $vars['finished']=1;
    	}
    }
}

class Subscription {

  function &getRecord($paypal_subscription_id) {
       return DBC::FindRecord("
       SELECT S.* FROM sport_subscriptions S
       WHERE S.paypal_subscription_id =". DBC::makeLiteral($paypal_subscription_id));
  }

  function &getID($paypal_subscription_id) {
       $id = 0;
       $rs =& DBC::FindRecord("
       SELECT S.id FROM sport_subscriptions S
       WHERE S.paypal_subscription_id =". DBC::makeLiteral($paypal_subscription_id));
       if ($rs) $id = $rs->get('id');
       return $id;
  }

  function existSubscription($paypal_subscription_id) {
       $rs =& DBC::FindRecord("
       SELECT S.* FROM sport_subscriptions S
       WHERE S.paypal_subscription_id =". DBC::makeLiteral($paypal_subscription_id));
       return !is_null($rs);
  }

  // checks whether exists, if exists - update
  function insertSubscription(&$data) {
  		$paypal_subscription_id = $data->get('paypal_subscription_id');
  		$exist = Subscription::existSubscription($paypal_subscription_id);
  		if ( $exist ) {
  			Subscription::updateSubscription($data);
  			$id = Subscription::getID( $paypal_subscription_id );
  			return $id;
  		}
        $Record =& DBC::NewRecord($data);
        $id = $Record->insertId('sport_subscriptions',
            array('paypal_subscription_id','start_date', 'end_date',
            'type', 'amount', 'recurring','status','reason','next_rebill_date','user_id'),'id');
        return $id;
  }

  // checks whether exists, if exists - exit
  function addSubscription($paypal_subscription_id, $user_id) {
  	$exist = Subscription::existSubscription($paypal_subscription_id);
  	if ( $exist ) {
  		$id = Subscription::getID( $paypal_subscription_id );
  		return $id;
  	}

    $data =& new DataSpace();
  	$data->set('paypal_subscription_id', $paypal_subscription_id);
  	$data->set('user_id', $user_id);
    $Record =& DBC::NewRecord($data);
    $id = $Record->insertId('sport_subscriptions',
            array('paypal_subscription_id', 'user_id'),'id');
    return $id;

  }

  function updateSubscription(&$data) {
        $paypal_subscription_id = $data->get('paypal_subscription_id');
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_subscriptions',
            array('paypal_subscription_id','start_date', 'end_date',
            'type', 'amount', 'recurring','status','reason','next_rebill_date','user_id'),
            "paypal_subscription_id = ". DBC::makeLiteral($paypal_subscription_id));
  }

  function cancelSubscription($paypal_subscription_id, $reason) {
  		$data =& new DataSpace();
  		$data->set('status', 0);
        $data->set('reason', $reason);
        $tz =& new MyTimeZone();

        $now = $tz->timeNowLocal();
        $mydate = gmdate('Y-m-d',$now);
        $data->set('end_date', $mydate);

        $Record =& DBC::NewRecord($data);
        if ($reason) $Record->update('sport_subscriptions',
            array('status', 'reason', 'end_date'), "paypal_subscription_id = ". DBC::makeLiteral($paypal_subscription_id));
        else $Record->update('sport_subscriptions',
            array('status', 'end_date'), "paypal_subscription_id = ". DBC::makeLiteral($paypal_subscription_id));
  }

  function updateSubscriptionRebillDate($paypal_subscription_id, $rebill_date) {
  		$data =& new DataSpace();
  		$data->set('next_rebill_date', $rebill_date);

        $Record =& DBC::NewRecord($data);
        $Record->update('sport_subscriptions',
            array('next_rebill_date'),
            "paypal_subscription_id = ". DBC::makeLiteral($paypal_subscription_id));
  }

  function updateSubscriptionReason($paypal_subscription_id, $reason) {
  		$data =& new DataSpace();
  		$data->set('reason', $reason);

        $Record =& DBC::NewRecord($data);
        $Record->update('sport_subscriptions',
            array('reason'),
            "paypal_subscription_id = ". DBC::makeLiteral($paypal_subscription_id));
  }

  //  $paymentTS - payment timestamp
  // gets the next rebill date - for the existing subscriptions
  function getNextRebillDate($paypal_subscription_id, $paymentTS) {
  	$record =& Subscription::getRecord($paypal_subscription_id);
  	if (is_null($record) ) return time();
  	$start_date = $record->get('start_date');
    $start_dateTS = strtotime( $start_date);
    $tz =& new MyTimeZone();
    $start_dateTS = $tz->timeGMT($start_dateTS);
    $recurring = $record->get('recurring');
    $type =  $record->get('type');
    if (!$recurring) {
    	$TS = Subscription::getExpirationDate($type, $start_dateTS);
    	return $TS;
    }
    $day = gmdate('d', $start_dateTS);
    $month = gmdate('m', $start_dateTS);
    $year = gmdate('Y', $start_dateTS);
    $myTS = $start_dateTS;
    while( $myTS < $paymentTS) {
    	if ($type == 3) $month++;
        if ($type == 4) $year++;
    	$myTS = gmmktime(0,0,0, $month, $day, $year);
        $myTS = $tz->timeLocal($myTS);
    }
    return $myTS;

  }

  // gets the subscription expiration date based on the type and timestamp
  function getExpirationDate($type, $myTS) {
    $day = (integer)gmdate('d', $myTS);
    $month = (integer)gmdate('m', $myTS);
    $year = (integer)gmdate('Y', $myTS);
    //$expireTS = time();
    $tz =& new MyTimeZone();
    $expireTS = $tz->timeNowLocal();
  	switch ($type) {
    	case 1:
            $day +=3;
      		break;
    	case 2:
            $day +=7;
      		break;
    	case 3:
            $month +=1;
      		break;
        case 4:
            $year +=1;
      		break;
  	}
  	$expireTS = gmmktime(0,0,0, $month, $day, $year);
    $expireTS = $tz->timeLocal($expireTS);
    return $expireTS;
  }

 // get subscriptions for user
 function &getListForUser($user_id, &$Pager) {
 	if($Pager==null)
 		return DBC::NewRecordSet(
        		'SELECT S.*, U.*, count(S.id) as number_subscriptions, count(P.payment_id) as number_payments
        		FROM sport_subscriptions S
                inner join sport_users U
        		on S.user_id = U.user_id
        		left outer join sport_payments P on S.id = P.subscription_id
        		where S.user_id = '. DBC::makeLiteral($user_id). '
        		group by S.id
        		order BY S.start_date desc',new SubscriptionFilter());
 	else
        return DBC::NewPagedRecordSet(
        		'SELECT S.*, U.*, count(S.id) as number_subscriptions, count(P.payment_id) as number_payments
        		FROM sport_subscriptions S
                inner join sport_users U
        		on S.user_id = U.user_id
        		left outer join sport_payments P on S.id = P.subscription_id
        		where S.user_id = '. DBC::makeLiteral($user_id). '
        		group by S.id
       		order BY S.start_date desc', $Pager);
    }

 function getSubscriptionsCount($user_id){
	return DBC::getOneValue("Select count(*) from sport_subscriptions where user_id=".DBC::makeLiteral($user_id));
 }


// 1 - 3-days one-time
// 2 - 7-days one-time
// 3 - 30-days recurring
// 4 - 1 year recurring
function &getHumanType($type) {
	if ($type==1) return '3-days one-time';
	elseif ($type==2) return '7-days one-time';
    elseif ($type==3) return '30-days recurring';
    elseif ($type==4) return '1-year recurring';
    else  return 'N/A';
}

// 1 - Active
// 0 - Finished
function &getHumanStatus($status) {
	if ($status==1) return 'Active';
	elseif ($status==0) return 'Finished';
    else  return 'N/A';
}

function getPrices(&$responsemodel) {
	$rs =& DBC::NewRecordSet(
	'select * from sport_prices');
	$rs->reset();
	// default values
	$responsemodel->set('type1', 5);
	$responsemodel->set('type2', 10);
	$responsemodel->set('type3', 20);
    $responsemodel->set('type4', 200);


	while($rs->next()) {
		$type = $rs->get('type');
		$price = number_format($rs->get('price'),2);
		$mytype = 'type'.$type;
        $responsemodel->set($mytype, $price);
	}
}

function savePrice($type,$price) {
	DBC::execute("DELETE FROM sport_prices WHERE `type`=". DBC::makeLiteral($type));
	$data =& new DataSpace();
	$props = array('type'=>$type, 'price'=>$price);
	$data->import($props);
	$Record =& DBC::NewRecord($data);
	$Record->insert('sport_prices', array('type','price'));
}


}

?>